package com.shyfu.dao;

import com.shyfu.entities.Author;
import com.shyfu.entities.Book;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by Svitlana on 04-Apr-14.
 */
@Repository
public class AuthorDAOImpl implements AuthorDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void addAuthor(Author author) {
        sessionFactory.getCurrentSession().save(author);
    }

    @Override
    public void removeAuthor(Author author) {
        sessionFactory.getCurrentSession().delete(author);
    }

    @Override
    public void removeAuthor(long id) {
        Author author = getAuthor(id);
        if (author != null) {
            removeAuthor(author);
        }
    }

    public void updateBook(Book book) {
        sessionFactory.getCurrentSession().update(book);
    }

    @Override
    public List<Author> getAllAuthors() {
        return sessionFactory.getCurrentSession().createQuery("from Author order by firstName,lastName").list();
    }

    @Override
    public Author getAuthor(long id) {
        return (Author) sessionFactory.getCurrentSession().load(Author.class, id);
    }
}
